<?php
session_start();
if ($_SESSION['user'] == "") {
    ?>
    <script>
        alert('当前未登录！');
        window.location.href = '../login.html';
    </script>
    <?php
}
try {
$db = new PDO('mysql:dbname=liaotian;host=106.14.7.147', 'root', '123456');
//查询在线人数是否小于限制人数
$searchNum = $db->prepare('select Num,roomNum from room where roomId=:roomId');
$data[':roomId'] = $_GET['roomId'];
if ($searchNum->execute($data) === false) {
    print_r($searchNum->errorInfo());
}
$reNum = $searchNum->fetch();
if ($reNum['Num'] >= $reNum['roomNum']) {
    ?>
    <script>
        alert('人数已满，不能进入');
        window.location.href = 'room.php?username=<?=$_SESSION['user']?>';
    </script>
    <?php
} else {
    $search = $db->prepare('select username,roomId,status from user_room WHERE username=:username ');
    $ee = $search->execute([
        ':username' => $_SESSION['user']
    ]);
    $reSearch = $search->fetch();
    if ($reSearch) {
        if ($_SESSION['user'] == $reSearch[0]) {
            $search = $db->prepare('select status from user_room WHERE username=:username ');
            $ee = $search->execute([
                ':username' => $_SESSION['user']
            ]);
            $reStatus = $search->fetch();
            //在线人数Num+1
            if ($reStatus[0] == 0) {
                $reNum['Num'] = $reNum['Num'] + 1;
                //在room表中更新在线人数 Num+1
                $update = $db->prepare('UPDATE room set Num=:Num WHERE roomId=:roomId');
                $data = [
                    ':roomId' => $_GET['roomId'],
                    ':Num' => $reNum['Num']
                ];
                if ($update->execute($data) === false) {
                    print_r($update->errorInfo());
                }
                $re = $update->fetch();
                //在user_room表中更新status=1,说明进入房间
                $update = $db->prepare('UPDATE user_room set status=:status,roomId=:roomId 
                                    WHERE username=:username');
                $data = [
                    ':username' => $reSearch['username'],
                    ':status' => 1,
                    ':roomId' => $_GET['roomId']
                ];
                if ($update->execute($data) === false) {
                    print_r($update->errorInfo());
                }
            } else {
                //在user_room表中更新status=1,说明进入房间
                $update = $db->prepare('UPDATE user_room set status=:status,roomId=:roomId 
                                    WHERE username=:username');
                $data = [
                    ':username' => $reSearch['username'],
                    ':status' => 1,
                    ':roomId' => $_GET['roomId']
                ];
                if ($update->execute($data) === false) {
                    print_r($update->errorInfo());
                }
            }
        }
    } else {
        if ($_SESSION['user'] != $reSearch[0]) {
            //在线人数Num+1
            $search = $db->prepare('select * from user_room WHERE username=:username ');
            $ee = $search->execute([
                ':username' => $_SESSION['user']
            ]);
            $reStatus = $search->fetch();
            $reNum['Num'] = $reNum['Num'] + 1;
            //在room表中更新在线人数 Num+1
            $update = $db->prepare('UPDATE room set Num=:Num WHERE roomId=:roomId');
            $data = [
                ':roomId' => $_GET['roomId'],
                ':Num' => $reNum['Num']
            ];
            if ($update->execute($data) === false) {
                print_r($update->errorInfo());
            }
            $re = $update->fetch();
            //添加user_room中的用户名称username
            $add = $db->prepare('INSERT INTO user_room (roomId,username,status) VALUES(:roomId,:username,:status)');
            $data = [
                ':username' => $_SESSION['user'],
                ':roomId' => $_GET['roomId'],
                ':status' => 1
            ];
            if ($add->execute($data) === false) {
                print_r($add->errorInfo());
            }
            $reAdd = $add->fetch();
        }
    }

}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <link href="../css/liaotianRoom.css" rel="stylesheet" type="text/css">
    <link type="image/x-icon" rel="shortcut icon" href="../../favicon.ico" />
</head>
<body>

<form method="post" id="myForm" action="/action/insertLiaotian.php">
    <div id="liaotian">
        <?php
        $search = $db->prepare('select roomName from room where roomId=:roomId');
        $data = [
            ':roomId' => $_GET['roomId']
        ];
        if ($search->execute($data) === false) {
            print_r($search->errorInfo());
        }
        $re = $search->fetchAll();
        foreach ($re as $list){
        ?>
        <div class="top" id="numShuxin">
            <div class="top_left">
                <?="$list[roomName]";?>聊天室
            </div>
            <div class="top_right">
                <div class="renshu">
                    在线人数:
                <span  id="chatNum">

                </span>
                </div>
                <div class="tui">
                    <a href="room.php?username=<?=$_SESSION['user'];?>">退出</a>
                </div>
                <div style="clear: both;"></div>
            </div>
            <div style="clear: both;"></div>
        </div>
        <?php }?>
        <div class="center">
            <div class="left">
                <div id="searchMessage" class="center_top">
                </div>
                <div class="center_foot">
                    <div class="foot_left">
                    <textarea name="content">

                    </textarea>
                    </div>
                    <div class="foot_right">
                        <input id="submit" class="fasong" type="submit" value="发送">
                    </div>
                    <div style="clear:both;"></div>
                </div>
            </div>
            <div class="right" id="userShuxin">

            </div>
            <div style="clear: both;"></div>
        </div>
</form>
<?php
} catch (PDOException $e) {
    echo 'Connection failed';
}
?>

<script>

    //在线数量同步信息
    var roomId =<?php echo $_GET['roomId']; ?>;
    var messageRoom = function () {
        var searchMessage = document.getElementById('chatNum');
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (this.readyState == 4) {
                if (this.status != 200) {
                    console.log("服务器异常！");
                } else {
                    var result = JSON.parse(this.responseText);
                    searchMessage.innerHTML = "";
                    if (result.message.length == 0) return;
                    for (var i = 0; i < result.message.length; i++) {
                        searchMessage.insertAdjacentHTML('beforeend',
                            result.message[i]
                        )
                    }
                }
            }
        };
        xhr.open('post', '/action/messageNum.php?roomId='+roomId);
        xhr.send();
    };
    setInterval(messageRoom, 1000);
    
    //用户在线同步信息
    var roomId =<?php echo $_GET['roomId']; ?>;
    var messageUser = function () {
        var searchMessage = document.getElementById('userShuxin');
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (this.readyState == 4) {
                if (this.status != 200) {
                    console.log("服务器异常！");
                } else {
                    var result = JSON.parse(this.responseText);
                    searchMessage.innerHTML = "";
                    if (result.message.length == 0) return;
                    for (var i = 0; i < result.message.length; i++) {
                        searchMessage.insertAdjacentHTML('beforeend',
                            '<div class="right_1">'+
                            '<div class="right_img">'+
                            '<img src="'+result.message[i].userImg+'"/>'+
                            '</a>'+
                            '</div>'+
                            '<div class="right_name">'+
                            result.message[i].nicheng+
                            '</a>'+
                            '</div>'+
                            '<div style="clear:both;"></div>'+
                            '</div>'
                        )
                    }
                }
            }
        };
        xhr.open('post', '/action/messageRight.php?roomId=' + roomId);
        xhr.send();
    };
    setInterval(messageUser, 1000);
    //控制滚动条下滑
    function send() {
        var e = document.getElementById("char");
        var inp = document.getElementById("message");
        e.innerText = e.innerText + "\n" + inp.value;
        //e.scrollTop=e.scrollHeight;
    }
    function sc() {
        var e = document.getElementById("char");
        e.scrollTop = e.scrollHeight;
    }
    var s = setInterval("sc()", 20000);

    //同步聊天框信息
    var roomId =<?php echo $_GET['roomId']; ?>;
    var username2='<?php echo $_SESSION['user']; ?>';
    var lastTime=<?php echo time(); ?>;
    var messageSubmit = function () {
        var searchMessage = document.getElementById('searchMessage');
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (this.readyState == 4) {
                if (this.status != 200) {
                    console.log("服务器异常！");
                } else {
                    var result = JSON.parse(this.responseText);
                    if (result.message.length == 0) return;
                    lastTime=result.time;
                    for (var i = 0; i < result.message.length; i++) {
                        var date=new Date;
                        var y=date.getFullYear(result.message[i].time);
                        var m=date.getMonth(result.message[i].time)+1;
                        var d=date.getDay(result.message[i].time);
                        var h=date.getHours(result.message[i].time);
                        var M=date.getMinutes(result.message[i].time);
                        var s=date.getSeconds(result.message[i].time);
                        if (result.message[i].username != username2) {
                            searchMessage.insertAdjacentHTML('beforeend',
                                '<div class="left_1">' +
                                '<div class="left_img">' +
                                '<div class="left_img_1">' +
                                '<img src="' + result.message[i].userImg + '"/>' +
                                '</div>' +
                                '<div class="left_img_2">' +
                                result.message[i].nicheng +
                                '</div>' +
                                '</div>' +
                                '<div class="left_content">' +
                                '<div class="left_content_date">'+
                                '<span>'+y+'-'+m+'-'+d+' '+h+':'+M+':'+s+'</span>'+
                                '</div>'+
                                '<div class="content_1">' +
                                '<span>' + result.message[i].content + '</span>' +
                                '</div>' +
                                '</div>' +
                                '<div style="clear: both;"></div>' +
                                '</div>'
                            )
                        } else {
                            searchMessage.insertAdjacentHTML('beforeend',
                                '<div class="left_right_name">' +
                                '<div class="left_content2">' +
                                '<div class="left_content_date2">'+
                                '<span>'+y+'-'+m+'-'+d+' '+h+':'+M+':'+s+'</span>' +
                                '</div>'+
                                '<div class="content_2">' +
                                '<span>' + result.message[i].content + '</span>' +
                                '</div>' +
                                '</div>' +
                                '<div class="left_img2">' +
                                '<div class="left_img_2">' +
                                '<img src="' + result.message[i].userImg + '"/>' +
                                '</div>' +
                                '<div class="left_img_3">' +
                                result.message[i].nicheng +
                                '</div>' +
                                '</div>' +
                                '<div style="clear: both;"></div>' +
                                '</div>'
                            )
                        }
                    }
                }
            }
        };
        xhr.open('post', '/action/messageLeft.php?lastTime='+lastTime+'&roomId=' + roomId);
        xhr.send();
    };
    setInterval(messageSubmit, 1000);
    //控制滚动条下滑
    function send() {
        var e = document.getElementById("searchMessage");
        var inp = document.getElementById("message");
        e.innerText = e.innerText + "\n" + inp.value;
        //e.scrollTop=e.scrollHeight;
    }
    function sc() {
        var e = document.getElementById("searchMessage");
        e.scrollTop = e.scrollHeight;
    }
    var s = setInterval(sc(), 120000);

    //发送信息
    var roomId = '<?php echo $_GET['roomId']; ?>';
    var username = '<?php echo $_SESSION['user']; ?>';
    var submitButton = document.getElementById('submit');
    var messageElement = document.getElementById('message');
    var myFormElement = document.getElementById('myForm');
    submitButton.onclick = function (e) {
        e.preventDefault();
        var elementUsername = document.querySelector('#myForm textarea[name=content]');
        var content = elementUsername.value;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (this.readyState == 4) {
                if (this.status == 200) {
                    var result = JSON.parse(this.responseText);
                    if (result.error == 1) {
                        alert(result.message);
                    } else {
                        elementUsername.value = "";
                        messageSubmit();
                    }
                } else {
                    console.log("异常");
                }
            }
        };
        xhr.open(myFormElement.method, myFormElement.action);
        var data = new FormData();
        data.append('roomId', roomId);
        data.append('username', username);
        data.append('content', content);
        xhr.send(data);
    }
</script>
</body>
</html>